package com.yyk.yiliao.ui.home.activity;

import android.app.Dialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectChangeListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.orhanobut.hawk.Hawk;
import com.orhanobut.logger.Logger;
import com.yyk.yiliao.R;
import com.yyk.yiliao.base.BaseActivity;
import com.yyk.yiliao.bean.MymessageVisitaddInfo;
import com.yyk.yiliao.listener.OneValueListenter;
import com.yyk.yiliao.util.Md5Util2;
import com.yyk.yiliao.util.TimeUtil;
import com.yyk.yiliao.util.ToastUtil;
import com.yyk.yiliao.util.DialogUtil;
import com.yyk.yiliao.util.ebs.MessageEvent;
import com.yyk.yiliao.util.rx.ApiService;
import com.yyk.yiliao.util.rx.RxUtils;
import com.yyk.yiliao.bean.MymessagePatientadd_Info;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Date;
import java.util.Map;
import java.util.TreeMap;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 添加就诊成员 ，有身份证的关系 除了没有子女
 */
public class AddMember_Activity extends BaseActivity {
    public static AddMember_Activity INTANSE;


    @BindView(R.id.rl_one)
    RelativeLayout rlOne;
    @BindView(R.id.rl_two)
    RelativeLayout rlTwo;
    @BindView(R.id.rl_three)
    RelativeLayout rlThree;
    @BindView(R.id.rl_four)
    RelativeLayout rlFour;
    @BindView(R.id.rl_five)
    RelativeLayout rlFive;
    @BindView(R.id.rl_six)
    RelativeLayout rlSix;
    @BindView(R.id.rl_seven)
    RelativeLayout rlSeven;
    @BindView(R.id.rl_eight)
    RelativeLayout rlEight;

    @BindView(R.id.tv_one) //关系名称
            TextView tvOne;
    @BindView(R.id.tv_two) //姓名
            EditText tvTwo;
    @BindView(R.id.tv_three)//身份证号
            EditText tvThree;
    @BindView(R.id.tv_four)//手机号
            EditText tvFour;
    @BindView(R.id.tv_five)//出生日期
            TextView tvFive;
    @BindView(R.id.tv_six) //性别
            TextView tvSix;
    @BindView(R.id.tv_seven) //看护人姓名
            EditText tvSeven;
    @BindView(R.id.tv_eight) //看护人身份证好
            EditText tvEight;

    @BindView(R.id.ll_wu)
    LinearLayout llWu;
    @BindView(R.id.bt_commit)
    Button btCommit;


    private String message;
    String timeS; //时间戳
    private int typNumber; //判断点击提交

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(mActivity);
    }

    @Override
    public int getLayoutId() {

        return R.layout.activity_add_member;
    }

    @Override
    public void initView() {
        initToolbar();
        initTimePicker();
    }

    private void initToolbar() {
        setBackArrow();
        setTitle("添加就诊成员");
    }


    @Override
    public void initData() {
        INTANSE = this;
        EventBus.getDefault().register(mActivity);

    }

    /**
     * 获取传回来的关系名称
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMevent(MessageEvent event) {
        message = event.getMessage();
        tvOne.setText(message);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (message != null) {
            if (message.equals("子女(未领取身份证)")) {
                llWu.setVisibility(View.VISIBLE);
                rlThree.setVisibility(View.GONE);
                typNumber = 2;
            } else {
                llWu.setVisibility(View.GONE);
                rlThree.setVisibility(View.VISIBLE);
                typNumber = 1;
            }
        }
    }


    /**
     * 添加人员信息
     *
     * @param typeNumber
     */
    private void initCommit(int typeNumber) {
        String type = tvOne.getText().toString().trim();//名称类型
        String name = tvTwo.getText().toString().trim();//姓名
        String patient_phone = tvFour.getText().toString().trim(); //手机号

        String sfz = tvThree.getText().toString().trim(); //身份证号

        String csrq = tvFive.getText().toString().trim(); //出生日期
        String sex = tvSix.getText().toString().trim();//性别
        String sname = tvSeven.getText().toString().trim();//看护人姓名
        String id_card2 = tvEight.getText().toString().trim();//看护人身份证号
        if (type.equals("请选择与本人关系")) {
            ToastUtil.showShort(mActivity, "请选择联系人关系");
            return;
        }
        if (TextUtils.isEmpty(name)) {
            ToastUtil.showShort(mActivity, "请输入正确的姓名");
            return;
        }

        if (patient_phone.length() != 11) {
            ToastUtil.showShort(mActivity, "请输入正确的手机号码");
            return;
        }

        /**
         * 添加 成年 信息
         */
        switch (typeNumber) {
            case 1:
                if (sfz.length() != 15 && sfz.length() != 18) {
                    ToastUtil.showShort(mActivity, "请输入正确的身份证号码");
                    return;
                }
                Map<String, String> map = new TreeMap<>();

                if (type.equals("本人")) {
                    map.put("type", 1 + "");
                } else if (type.equals("父母")) {
                    map.put("type", 2 + "");
                } else if (type.equals("夫妻")) {
                    map.put("type", 3 + "");
                } else if (type.equals("子女(已领取身份证")) {
                    map.put("type", 4 + "");
                } else if (type.equals("子女(未领取身份证")) {
                    map.put("type", 5 + "");
                } else {
                    map.put("type", 6 + "");
                }
                map.put("real_name", name);
                map.put("id_card", sfz);
                map.put("patient_phone", patient_phone);
                map.put("user_id", Hawk.get("uid", 0) + "");
                map.put("sign", Md5Util2.createSign(map));

                setCommit(map, typeNumber);
                break;
            /**
             * 添加 未成年 子女信息
             */
            case 2:
                if (TextUtils.isEmpty(csrq)) {
                    ToastUtil.showShort(mActivity, "请输入出生日期");

                    return;
                }
                if (TextUtils.isEmpty(sex)) {
                    ToastUtil.showShort(mActivity, "请输入性别");

                    return;
                }
                if (TextUtils.isEmpty(sname)) {
                    ToastUtil.showShort(mActivity, "请输入看护人姓名");
                    return;
                }
                if (id_card2.length() != 15 && id_card2.length() != 18) {
                    ToastUtil.showShort(mActivity, "请输入正确的看护人身份证号码");
                    return;
                }
                Map<String, String> map2 = new TreeMap<>();
                if (type.equals("子女(未领取身份证)")) {
                    map2.put("noidcard_type", 5 + "");
                }
                map2.put("noidcard_user", sname + "");
                map2.put("noidcard_card", id_card2 + "");
                map2.put("noidcard_phone", patient_phone + "");
                if (sex.equals("女")) {
                    map2.put("sex", 2 + "");
                } else {
                    map2.put("sex", 1 + "");
                }
                map2.put("birth", timeS + "");
                Logger.e("birth__" + timeS);
                map2.put("name", name);
                map2.put("user_id", Hawk.get("uid", 0) + "");
                map2.put("sign", Md5Util2.createSign(map2));
                setCommit(map2, typeNumber);
                break;

        }
    }


    public void setCommit(Map<String, String> map, int typeNumber) {
        switch (typeNumber) {
            case 1:
                RxUtils.getInstance().retrofit.create(ApiService.class).postMymessageVisitadd(map)
                        .subscribeOn(Schedulers.io())     //调度线程
                        .observeOn(AndroidSchedulers.mainThread())
                        .unsubscribeOn(Schedulers.io())   //取消订阅
                        .subscribe(new Subscriber<MymessageVisitaddInfo>() {

                            @Override
                            public void onCompleted() {
                                //完成的时候调用
                            }

                            @Override
                            public void onError(Throwable e) {
                                e.printStackTrace();

                            }

                            @Override
                            public void onNext(MymessageVisitaddInfo info) {
                                if (info.getCode() == 1) {
                                    ToastUtil.showShort(mActivity, "添加联系人成功");
                                    finish();
                                }
                            }
                        });
                break;
            case 2:
                RxUtils.getInstance().retrofit.create(ApiService.class).postMymessagePatientadd(map)
                        .subscribeOn(Schedulers.io())     //调度线程
                        .observeOn(AndroidSchedulers.mainThread())
                        .unsubscribeOn(Schedulers.io())   //取消订阅
                        .subscribe(new Subscriber<MymessagePatientadd_Info>() {

                            @Override
                            public void onCompleted() {
                                //完成的时候调用

                            }

                            @Override
                            public void onError(Throwable e) {
                                e.printStackTrace();

                            }

                            @Override
                            public void onNext(MymessagePatientadd_Info info) {
                                Logger.d("添加子女关系"+info.toString());
                                if (info.getCode() == 1) {
                                    ToastUtil.showShort(mActivity, "添加联系人成功");
                                    finish();
                                }
                            }


                        });
                break;

        }

    }


    /**
     * 时间选择器
     */
    private TimePickerView pvTime;

    /**
     * 请求时间框
     */
    private void initTimePicker() {//Dialog 模式下，在底部弹出

        pvTime = new TimePickerBuilder(this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
//                Toast.makeText(AddMember2_Activity.this, getTime(date), Toast.LENGTH_SHORT).show();
                Log.i("pvTime", "onTimeSelect");
                timeS = String.valueOf(date.getTime() / 1000);
//                String time = getTime(date);
                String time = TimeUtil.getInstance().getTime((int) (date.getTime() / 1000), TimeUtil.YYYY_MM_DD);
//  绑定不了
//  ((TextView) v).setText(time);
                tvFive.setText(time);

            }
        })
                .setTimeSelectChangeListener(new OnTimeSelectChangeListener() {
                    @Override
                    public void onTimeSelectChanged(Date date) {
                        Log.i("pvTime", "onTimeSelectChanged");
                    }
                })
                .setType(new boolean[]{true, true, true, false, false, false})
                .isDialog(true) //默认设置false ，内部实现将DecorView 作为它的父控件。
                .setLineSpacingMultiplier(2.0f) //设置间距
                .build();
        Dialog mDialog = pvTime.getDialog();
        if (mDialog != null) {

            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    Gravity.BOTTOM);

            params.leftMargin = 0;
            params.rightMargin = 0;
            pvTime.getDialogContainerLayout().setLayoutParams(params);

            Window dialogWindow = mDialog.getWindow();
            if (dialogWindow != null) {
                dialogWindow.setWindowAnimations(com.bigkoo.pickerview.R.style.picker_view_slide_anim);//修改动画样式
                dialogWindow.setGravity(Gravity.BOTTOM);//改成Bottom,底部显示
            }
        }
    }

    /**
     * 性别选择框
     */
    private void showSexChooseDialog() {
        DialogUtil.getIntanse().showSexChooseDialog(mActivity, new OneValueListenter() {
            @Override
            public void onClickListenter(String message) {
                tvSix.setText(message);

            }
        });
    }

    /**
     * 1.选择 关系列表
     * 3.弹出性别对话框
     * 2.弹出时间选择器
     * 4.提交资料
     *
     * @param view
     */
    @OnClick({R.id.rl_one, R.id.rl_five, R.id.rl_six, R.id.bt_commit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_one:
                startAct(RelationshipM_Activity.class);

                break;
            case R.id.rl_five:
                pvTime.show(view);//弹出时间选择器，传递参数过去，回调的时候则可以绑定此view
                break;
            case R.id.rl_six:
                showSexChooseDialog();
                break;
            case R.id.bt_commit:
                //根据传入的位置判断
                initCommit(typNumber);
                break;
        }
    }


}
